
// "ui";
//require("./modules/rightToMention");
toast("请开启喵糖的无障碍服务\n若开启后没有反应，请关闭后重新开启");
auto.waitFor();

dialogs.build({
    //对话框标题
    title: "喵糖自动浏览脚本V1.2.3",
    //对话框内容
    content: "更新日志: \n1. 修复了某些情况下去浏览会立即自动返回的bug\n" + 
    "2. 增加更新日志",
    //确定键内容
    positive: "确定",
    neutral: "打开官网"
}).on("neutral", () => {
    app.openUrl("https://gitee.com/duguxt/taobao-meow-sugar-task/releases");
}).show();

var w = floaty.window(
    <vertical gravity="center">
        <button style="Widget.AppCompat.Button.Colored" id="start">开始脚本</button>
        <button style="Widget.AppCompat.Button.Colored" id="stop">停止脚本</button>
        <button style="Widget.AppCompat.Button.Colored" id="exit">退出</button>
    </vertical>
);

// 任务线程
var threadRun = threads.start(null);

w.start.click(function () {
    if (threadRun.isAlive()) {
        toast("脚本已在运行！");
    } else {
        w.start.setEnabled(false);
        w.start.setText("正在运行");
        threadRun = threads.start(main);
    }
});

w.stop.click(function () {
    if (!threadRun.isAlive()) toast("脚本未运行");
    else {
        if (threadRun.isAlive())
            threadRun.interrupt();
        toast("脚本已停止");
        w.start.setText("开始脚本");
        w.start.setEnabled(true);
    }
});

w.exit.click(function () {
    toast("脚本运行结束");
    if (threadRun.isAlive())
        threadRun.interrupt();
    engines.myEngine().forceStop();
});


setInterval(() => {
    // 守护线程
    if (!threadRun.isAlive()) {
        w.start.setEnabled(true);
        w.start.setText("开始脚本");
    }
}, 1000);

function findTaskAndClick() {
    while (true) {
        var target;

        if (target = text("去浏览").findOnce()) {
            var title = target.parent().child(0).child(0).text()
            // var pat = /(\d+)\/\d+/;
            // results = pat.exec(title);
            // var times = parseInt(results[1]) + 1;
            toastLog("正在浏览：" + title);

            target.click();
            break;
        }

        target = textContains("逛逛").find();
        if (!target.empty()) {
            var found = false;
            // 遍历每个逛逛任务，寻找未完成的
            target.forEach(function (t) {
                if (t.parent().parent().findByText("已完成").empty) {
                    toastLog(t.text());
                    t.parent().parent().click();
                    found = true;
                    return;
                }
            })
            if (found) break;
        }

        if ((target = textContains("浏览天天").findOnce())) {
            if (target.parent().parent().findByText("已完成").empty) {
                toastLog(target.text());
                target.parent().parent().click();
                // log(className("android.view.View").text("打开链接").findOne().parent())
                sleep(1000);
                var uiObj = className("android.view.View").text("打开链接").findOne().parent();
                click(uiObj.bounds().centerX(), uiObj.bounds().centerY())
                break;
            }
        }

        target = textContains("浏览15").find();
        if (!target.empty()) {
            var found = false;
            // 遍历每个浏览15秒任务，寻找未完成的
            target.forEach(function (t) {
                if (t.parent().parent().parent().findByText("已完成").empty) {
                    toastLog(t.parent().parent().child(0).text());
                    t.parent().parent().parent().click();
                    found = true;
                    return;
                }
            })
            if (found) break;
        }

        sleep(200);
    }
}

/**
 * 
 * @param {Array<String>} strs 
 * @returns 
 */
function textOrDescContainsMulti(strs) {
    for (let str of strs) {
        if (textContains(str).exists() || descContains(str).exists()) {
            return true;
        }
    }
    return false;
}

function main() {
    toast("开始运行");
    var res = launchPackage("com.taobao.taobao");
    if (!res) {
        toast("淘宝启动失败！");
        exit();
    }

    let i = 0;
    while (true) {
        if (++i % 15 == 0)
            toast("如果长时间未进入活动界面，请手动点击进入");

        target = text("赚糖领红包").findOne(200);
        if (target) {
            target.click();
            break;
        }

        target = desc("赢20亿红包").findOne(200);
        if (target) {
            target.click();
        } else {
            target = desc("我的淘宝").findOne(200);
            if (target) {
                target.click();
            }
        }
    }

    sleep(2000);
    while (true) {
        findTaskAndClick();

        // 检查任务是否已完成
        var i = 0;
        while (!textOrDescContainsMulti(["任务已完成", "喵糖已发放"]) && (i++ < 110)) {
            sleep(200);
        }

        back();

        sleep(1500);
    }
}
